import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    products: [],
    totalPrice: 0
  },
  mutations: {
    ADD_PRODUCT(state, product) {
      const index = state.products.findIndex(p => p.id === product.id)
      if (index !== -1) {
        state.products[index].quantity += product.quantity
      } else {
        state.products.push(product)
      }
      state.totalPrice += product.price * product.quantity
    },
    REMOVE_PRODUCT(state, productId) {
      const index = state.products.findIndex(p => p.id === productId)
      if (index !== -1) {
        const product = state.products[index]
        state.totalPrice -= product.price * product.quantity
        state.products.splice(index, 1)
      }
    }
  },
  actions: {
    addProduct({ commit }, product) {
      commit('ADD_PRODUCT', product)
    },
    removeProduct({ commit }, productId) {
      commit('REMOVE_PRODUCT', productId)
    }
  },
  getters: {
    getProducts: state => state.products,
    getTotalPrice: state => state.totalPrice
  }
})
